﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System;

// ----------------------------------------------------------------------------------
//
// EncryptUtils
// Created by tzy - 2016 - 用于字符串加密
//
// ----------------------------------------------------------------------------------

public static class EncryptUtils {
    private static readonly string EncryptKey = "Monodevelop9Unity1File8Edit2View";

    private static RijndaelManaged CreateRijndael() {
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = UTF8Encoding.UTF8.GetBytes(EncryptKey);
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        return rDel;
    }

    public static byte[] Encrypt(byte[] data) {
        return CreateRijndael().CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
    }

    public static string Encrypt(string data) {
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(data);
        byte[] resultArray = Encrypt(toEncryptArray);
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    public static byte[] Decrypt(byte[] data) {
        return CreateRijndael().CreateDecryptor().TransformFinalBlock(data, 0, data.Length);
    }

    public static string Decrypt(string data) {
        byte[] toEncryptArray = Convert.FromBase64String(data);

        try {
            byte[] resultArray = Decrypt(toEncryptArray);
            return UTF8Encoding.UTF8.GetString(resultArray);
        } catch(Exception ex) {
            Debug.LogError("Decrypt data failed, reset data. " + ex.Message);
            return null;
        }
    }
}